#! /usr/bin/python
import csv
import math
import os
import time
import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
import pylab
figure0=plt.figure()
ploot=figure0.add_subplot(111)

event_limit=1000

class analysis:
	
	def begin(self):
		pass


	def event(self,input_filename):
		event_tuples = self.load_event(self.filedir+input_filename)
		self.event_analysis(event_tuples)
		

	def load_event(self,filename):
		#implement event loading
		pass

	def event_analysis(self,event_tuples):
		#implement event processing
		pass
		
	def cuts(self):
		#implement event cuts
		pass

	def write_output(self):
		#write data out
		pass
	
class waveform_analysis(analysis):


	def __init__(self,filedir, output_filename="NONE"):
		self.filedir=filedir
		self.output_filename=output_filename	

		#self.integral_limits=[50,125]
		self.pretrigger_samples=10
		self.amplitude_threshold=10*0.00034

		self.amplitude_sampstamps=[]
		self.amplitude_timestamps=[]
		self.threshold_sampstamps=[]
		self.threshold_timestamps=[]
		self.amplitude=[]
		self.total_integral=[]
		self.threshold_toend_integral=[]
		self.threshold_tolimit_integral=[]
		self.pretrig_mean=[]
		self.pretrig_rms=[]
		
		self.plotnum=0
		self.numcut=0
		self.event_index=0
		self.start_rms=[]
		self.start_mean=[]
		
		
	#----------Sets and Gets (Parameters)--------#
	def set_pretrigger_samples(self,samples):
		self.pretrigger_samples = samples

	def get_pretrigger_samples(self):
		return self.pretrigger_samples


	def set_amplitude_threshold(self,threshold):
		self.amplitude_threshold = threshold

	def get_amplitude_threshold(self):
		return self.amplitude_threshold	


	def set_integral_limits(self,low,high):
		self.integral_limits[0]=low
		self.integral_limits[0]=high

	def get_integral_limits(self):
		return self.integral_limits	
	#--------------------------------------------#
	def write_output(self):
			print(self.output_filename)
#			print("DOGS!!!!")
			print("NUMCUT:",self.numcut)
			if self.output_filename=="NONE":
				pass
			else:
				np.savez(self.output_filename,amp_timestamp=self.amplitude_timestamps,max_amp=self.amplitude,volt_integral=self.integral,sampstamps=self.amplitude_sampstamps)

	def file_loop(self):
		filelist = os.listdir(self.filedir)
		for filename in filelist:		
			if event_limit!=False:
				if self.event_index==event_limit:
						break
			if "Ch2" in filename:
				print("Event:",self.event_index,"Of:",len(filelist))
				self.event(filename)
		self.write_output()

	def begin(self):
		self.file_loop()			

	def load_event(self,filename):
		time, voltage = np.loadtxt(filename,delimiter=',',usecols=(3,4),unpack=True)
		return [time,voltage]
	
	def cuts(self,time,voltage):
		if math.fabs(np.min(voltage))>self.amplitude_threshold:
			return True
		else:
#			print("CUUUUT!")
			self.numcut+=1
			return False

	def event_analysis(self,event_tuples):
		time=event_tuples[0]
		voltage=event_tuples[1]
						
	#	baseline = np.mean(voltage[:self.pretrigger_samples])
	#	voltage_demeaned = [x-baseline for x in voltage]
		voltage_demeaned = voltage
	#	print("MEAN:",baseline)
	#	print(voltage[:self.pretrigger_samples])

#		np.savez("sheep.npz",np.arange(1,1001),voltage)
#			fig=plt.figure()
#			histo=fig.add_subplot(111)
#			plt.plot(time,voltage)
#			plt.show()
			
		print("SAMPLES:",len(voltage))

#		if self.cuts(time,voltage_demeaned)==True:
#		plt.plot(np.arange(0,200),voltage_demeaned[0:200])
#		plt.savefig("ploot"+str(self.plotnum)+".png")
#		plt.clf()
#		self.plotnum+=1


		if self.cuts(time,voltage_demeaned):
			print("PASSED")
			
			self.amplitude.append(math.fabs(min(voltage_demeaned)))
			self.pretrig_mean.append(np.mean(voltage_demeaned[:pretrigger_samples]))
			self.pretrig_rms.append(np.std(voltage_demeaned[:pretrigger_samples]))
			
			threshpass=0
			for sample in voltage_demeaned:
				if math.fabs(sample)>self.amplitude_threshold:
					break
				threshpass+=1
				
			self.threshold_sampstamps.append(threshpass)
			self.threshold_timestamps.append(time[threshpass])

			min_arg = np.argmin(voltage_demeaned)

			self.amplitude_timestamps.append(time[min_arg])
			
			self.amplitude_sampstamps.append(min_arg)

			if self.integral_limits[0]=="NONE":
				partial_sum = np.sum(voltage_demeaned)
			else:
				partial_sum = np.sum(voltage_demeaned[self.integral_limits[0]:self.integral_limits[1]])
#				print(len(voltage_demeaned[self.integral_limits[0]:self.integral_limits[1]]))
#				print("DOGE!!")
			delta_t = time[1]-time[0]

			thresh_sum_to_limit = np.sum(voltage_demeaned[threshpass:self.integral_limits[1]])
			thresh_sum_to_end = np.sum(voltage_demeaned[threshpass:])



			self.
			self.integral.append(partial_sum*delta_t)
			self.event_index+=1

			
class waveform_analysis_variancecut(waveform_analysis):
	
	def cuts(self,time,voltage):
		if math.fabs(min(voltage))<self.amplitude_threshold:
			self.numcut+=1
			return False
		elif math.fabs(np.min(voltage[:self.pretrigger_samples]))>self.amplitude_threshold:
			self.numcut+=1
			return False
		else:
			return True

'''			
class waveform_analysis_findvariance(waveform_analysis):

	self.variances
	self.mean_variance

	def event_analysis(self,event_tuples):
		time=event_tuples[0]
		voltage=event_tuples[1]
		event_index=0
		for event in event_tuples:
			if event_limit!=False:
				if event_index==event_limit:
					break
#			if self.variance_cut==True:
#				voltage_pretrig=voltage[event_index][:self.pretrig_samples]
#				if np.std(voltage_pretrig)>self.pretrigger_variance_threshold:
#					pass
#			self.amplitude.append(math.fabs(voltage)
					

			if cuts(time,voltage):
				self.variances.append(np.std(voltage))

				event_index+=1
				
		def cuts(time,voltage):
			return True
			
		def write_output(self):
			if self.output_filename=="NONE":
				pass
			else:
				np.savez(self.output_filename,mean_variance=self.mean_variance)
'''				
				


path = '/home/zander/MIT/fnal_summer_2014/AttenuationLength/'
dirname = 'Sipm2/'	

sipm2 = waveform_analysis(path+dirname,"sipm2_analysis_test.npz")
sipm2.begin()

'''
npzfile = np.load("Sipm7ch2.csv")
npzfile.files
'''
#
fig = plt.figure()
#fig2 = plt.figure()
#fig3 = plt.figure()
#fig3= plt.figure()


histo_amptrig = fig.add_subplot(111)

'''
plot_voltage = fig2.add_subplot(111)
plot_voltage.set_title("Voltage: Channel 2")    
plot_voltage.set_xlabel('Time')
plot_voltage.set_ylabel('Voltage')
#ax3 = fig2.add_subplot(122)
'''

histo_amptrig.set_title("Minimum ch2 voltage: SiPM3")
histo_amptrig.set_xlabel("Min Voltage")
histo_amptrig.set_ylabel("Counts")





'''
sipm2=analysis(path+dirname)
sipm2.read_file_list()
sipm2.set_trigger_threshold(5*0.00034)

sipm2.write_min_voltages('Sipm7')

'''
